﻿Public Class Factura
    Enum estado
        inicial
        insertar
        modificar
    End Enum
    Enum resultado
        exitoso
        erroneo
    End Enum
    Enum busqueda
        si_encontro
        no_encontro
    End Enum

    Dim operacion As estado = estado.inicial
    Dim datos_clase As New datos
    Dim tratamiento As New Tratamiento_Objetos

    Private Sub botones(ByVal flag As Boolean)
        Me.btn_nuevo.Enabled = flag
        Me.btn_salir.Enabled = flag
        Me.btn_cancelar.Enabled = Not flag
        Me.btn_guardar.Enabled = Not flag
        btn_buscar_cd.Enabled = Not flag
        btn_buscar_cliente.Enabled = Not flag
        btn_agregar.Enabled = Not flag
    End Sub

    Private Function validar_factura() As Boolean
        Dim flag As Boolean = True
        If cmb_tipo_factura.SelectedIndex = -1 Then
            flag = False
            cmb_tipo_factura.Focus()
        End If

        If cmb_tipo_pago.SelectedIndex = -1 Then
            flag = False
            cmb_tipo_pago.Focus()
        End If

        If String.IsNullOrEmpty(txt_nro_factura.Text) Then
            flag = False
            txt_nro_factura.Focus()
        End If

        If cmb_tipo_documento.SelectedIndex = -1 Then
            flag = False
            cmb_tipo_documento.Focus()
        End If

        If String.IsNullOrEmpty(txt_documento.Text) Then
            flag = False
            txt_documento.Focus()
        End If

        If String.IsNullOrEmpty(txt_apellido_cliente.Text) Then
            flag = False
            txt_apellido_cliente.Focus()
        End If

        If String.IsNullOrEmpty(txt_nombre_cliente.Text) Then
            flag = False
            txt_nombre_cliente.Focus()
        End If

        If Not IsDate(msk_fecha.Text) Then
            msk_fecha.Focus()
            flag = False
        Else
            Dim fechaActual As New Date
            fechaActual = Date.Now
            Dim fecha As Date
            fecha = Date.Parse(msk_fecha.Text)
            If fecha > fechaActual Then
                MessageBox.Show("Fecha no valida", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                lbl_fecha.ForeColor = Color.Red
                msk_fecha.Focus()
                flag = False
            End If
        End If

        Return flag
    End Function

    Private Sub habilitar_grupo_cliente(ByVal flag As Boolean)
        cmb_tipo_documento.Enabled = flag
        txt_documento.Enabled = flag
        txt_apellido_cliente.Enabled = flag
        txt_nombre_cliente.Enabled = flag
    End Sub

    Private Sub habilitar_grupo_cd(ByVal flag As Boolean)
        txt_codigo_cd.Enabled = flag
        txt_titulo_cd.Enabled = flag
        txt_precio_cd.Enabled = flag
        txt_cantidad.Enabled = flag
        txt_subtotal_cd.Enabled = flag
    End Sub

    Private Sub Factura_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        botones(True)
        cargarCombo(cmb_tipo_factura, "tipo_factura", "id_tipo_factura", "nombre")
        cargarCombo(cmb_tipo_pago, "tipo_pago", "id_tipo_pago", "nombre")
        cargarCombo(cmb_tipo_documento, "tipo_documento", "id_tipo_documento", "nombre")
        tratamiento.habilitar(False, Me.Controls)
        habilitar_grupo_cliente(False)
        habilitar_grupo_cd(False)

    End Sub

    Private Sub cargarCombo(ByRef combo As ComboBox, ByVal datos As DataTable, ByVal pk As String, ByVal descripcion As String)
        combo.Items.Clear()
        combo.DataSource = datos
        combo.ValueMember = pk
        combo.DisplayMember = descripcion
    End Sub

    Private Sub cargarCombo(ByRef combo As ComboBox, ByVal tabla As String, ByVal pk As String, ByVal descripcion As String)
        Dim data As Data.DataTable = datos_clase.leo_tabla(tabla)
        combo.Items.Clear()
        combo.DataSource = data
        combo.ValueMember = pk
        combo.DisplayMember = descripcion
        combo.SelectedIndex = -1
    End Sub

    Private Sub btn_nuevo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_nuevo.Click
        operacion = estado.insertar
        botones(False)
        tratamiento.habilitar(True, Me.Controls)
        habilitar_grupo_cd(True)
        habilitar_grupo_cliente(true)
        tratamiento.limpiar(Me.Controls)
        txt_cantidad.Enabled = True
        cmb_tipo_documento.Enabled = False
        msk_fecha.Text = Today.Date()
        cmb_tipo_factura.Focus()
    End Sub


    Private Sub btn_buscar_cliente_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar_cliente.Click
        Buscar_Clientes.ShowDialog()
    End Sub

    Private Sub btn_buscar_cd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar_cd.Click
        Buscar_CDs.ShowDialog()
    End Sub

    Private Sub txt_cantidad_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_cantidad.TextChanged
        Dim a, b As Double

        a = Val(txt_precio_cd.Text.Replace(",", "."))
        b = Val(txt_cantidad.Text.Replace(",", "."))

        txt_subtotal_cd.Text = a * b
    End Sub

    Private Function buscar_duplicado() As Integer
        Dim c As Integer
        Dim encontro As Boolean = False

        For c = 0 To Me.grilla1.RowCount - 1
            If Me.grilla1.Rows(c).Cells(1).Value.ToString.Trim = txt_codigo_cd.Text.Trim Then
                encontro = True
                Exit For
            End If
        Next
        If encontro = False Then
            Return -1
        End If
        Return c
    End Function

    Private Function calcular_total() As Double
        Dim c As Integer
        Dim calculo As Double
        calculo = 0
        For c = 0 To Me.grilla1.RowCount - 1
            calculo = calculo + Convert.ToDouble(Me.grilla1.Rows(c).Cells(4).Value)
        Next
        Return calculo
    End Function

    Private Function validar_cd() As Boolean
        Dim flag As Boolean = True
        If String.IsNullOrEmpty(txt_subtotal_cd.Text) Then
            flag = False
        End If
        If String.IsNullOrEmpty(txt_cantidad.Text) Then
            flag = False
        End If
        If String.IsNullOrEmpty(txt_precio_cd.Text) Then
            flag = False
        End If
        If String.IsNullOrEmpty(txt_titulo_cd.Text) Then
            flag = False
        End If
        If String.IsNullOrEmpty(txt_codigo_cd.Text) Then
            flag = False
        End If
        Return flag
    End Function

    Private Sub btn_agregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_agregar.Click
        If validar_cd() = True Then
            Dim fila As Integer = buscar_duplicado()

            If fila > -1 Then
                Me.grilla1.Rows(fila).Cells(0).Value = Convert.ToDouble(Me.grilla1.Rows(fila).Cells(0).Value) + Convert.ToDouble(Me.txt_cantidad.Text)
                Me.grilla1.Rows(fila).Cells(4).Value = Convert.ToDouble(Me.grilla1.Rows(fila).Cells(0).Value) * Convert.ToDouble(Me.txt_precio_cd.Text)
            Else
                Me.grilla1.Rows.Add(Convert.ToDouble(Me.txt_cantidad.Text), Convert.ToDouble(Me.txt_codigo_cd.Text) _
                                    , Me.txt_titulo_cd.Text, Convert.ToDouble(Me.txt_precio_cd.Text), Convert.ToDouble(Me.txt_subtotal_cd.Text))
            End If


            Me.txt_total.Text = calcular_total()
        Else
            MessageBox.Show("Complete todos los datos del CD!", "Notificación", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Private Sub btn_guardar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_guardar.Click
        If validar_factura() = True Then
            If grilla1.Rows.Count = 0 Then
                MessageBox.Show("Falta del Detalle de Factura!", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
                Exit Sub
            End If

            datos_clase.iniciar_conexion_transaccion()
            grabar_factura()
            grabar_detalle()

            Dim estado As Object
            estado = Me.datos_clase.finalizar_conexion_transaccion()

            If estado.ToString = "_ok" Then
                MsgBox("Se grabó exitosamente", MsgBoxStyle.Information, "Importante")
                operacion = Factura.estado.inicial
                botones(True)
                tratamiento.habilitar(False, Me.Controls)
                habilitar_grupo_cd(False)
                habilitar_grupo_cliente(False)
                tratamiento.limpiar(Me.Controls)
                tratamiento.limpiar(grp_cd.Controls)
                tratamiento.limpiar(grp_cliente.Controls)
                txt_cantidad.Enabled = False
                grilla1.Rows.Clear()
                btn_nuevo.Focus()
            Else
                MsgBox("Se produjo error en la grabación", MsgBoxStyle.Information, "Importante")
            End If
        Else
            MessageBox.Show("Complete todos los datos de la factura!", "Importante", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Private Sub grabar_factura()
        Dim txt As String = ""

        If operacion = estado.insertar Then
            txt = "insert into factura(id_tipo_factura,fecha,id_tipo_pago,numero_documento,id_tipo_documento,total) values ('"
            txt &= Me.cmb_tipo_factura.SelectedValue & "','" & Me.msk_fecha.Text & "','" & Me.cmb_tipo_pago.SelectedValue & "','"
            txt &= Me.txt_documento.Text & "','" & Me.cmb_tipo_documento.SelectedValue & "','" & Me.txt_total.Text.Replace(",", ".") & "')"
        Else
            txt = "update factura"
            txt &= " set fecha = '" & Me.msk_fecha.Text & "',"
            txt &= " id_tipo_pago = '" & Me.cmb_tipo_pago.SelectedValue & "',"
            txt &= " numero_documento = '" & Me.txt_documento.Text & "',"
            txt &= " id_tipo_documento = '" & Me.cmb_tipo_documento.SelectedValue & "',"
            txt &= " total = '" & Me.txt_total.Text.Replace(",", ".") & "'"
            txt &= " where numero_factura = '" & Me.txt_nro_factura.Text & "' and id_tipo_factura = '" & Me.cmb_tipo_factura.SelectedValue & "'"
        End If
        datos_clase.ejecutar(txt)
    End Sub

    Private Sub grabar_detalle()
        Dim c As Integer
        Dim txt As String = ""

        Me.borrar_detalle()

        For c = 0 To Me.grilla1.RowCount() - 1
            If buscar_detalle(Me.grilla1.Rows(c).Cells(1).Value) = busqueda.no_encontro Then
                txt = "insert into detalle_factura(numero_factura,id_tipo_factura,codigo_cd,cantidad,precio) values ('"
                txt &= Me.txt_nro_factura.Text & "','" & Me.cmb_tipo_factura.SelectedValue & "','"
                txt &= Me.grilla1.Rows(c).Cells("codigo_cd").Value & "','" & Me.grilla1.Rows(c).Cells("cantidad").Value.ToString.Replace(",", ".") & "','"
                txt &= Me.grilla1.Rows(c).Cells("precio").Value.ToString.Replace(",", ".") & "')"
            Else
                txt = "update detalle_factura"
                txt &= " set cantidad = '" & Me.grilla1.Rows(c).Cells("cantidad").Value.ToString.Replace(",", ".") & "',"
                txt &= " precio = '" & Me.grilla1.Rows(c).Cells("precio").Value.ToString.Replace(",", ".") & "'"
                txt &= " where numero_factura = '" & Me.txt_nro_factura.Text & "' and id_tipo_factura = '" & Me.cmb_tipo_factura.SelectedValue & "'"
                txt &= " and codigo_cd = '" & Me.grilla1.Rows(c).Cells("codigo_cd").Value & "'"
            End If
            Me.datos_clase.ejecutar(txt)
            txt = ""
        Next
    End Sub

    Private Sub borrar_detalle()
        Dim tabla As New Data.DataTable
        Dim sql, borrar As String
        Dim rgt, rgg As Integer
        Dim encontre As Boolean = False


        sql = "SELECT codigo_cd FROM detalle_factura "
        sql &= " WHERE numero_factura = " & Me.txt_nro_factura.Text
        sql &= " AND id_tipo_factura = " & Me.cmb_tipo_factura.SelectedValue

        tabla = datos_clase.consulta(sql)
        If tabla.Rows.Count() = 0 Then
            Exit Sub
        End If

        For rgt = 0 To tabla.Rows.Count() - 1
            encontre = False
            For rgg = 0 To Me.grilla1.RowCount() - 1
                If tabla.Rows(rgt)(0) = Me.grilla1.Rows(rgg).Cells(1).Value Then
                    encontre = True
                    Exit For
                End If
            Next
            If encontre = False Then
                borrar = "DELETE FROM detalle_factura "
                borrar &= " WHERE numero_factura = " & Me.txt_nro_factura.Text
                borrar &= " AND id_tipo_factura = " & Me.cmb_tipo_factura.SelectedValue
                borrar &= " AND codigo_cd = " & tabla.Rows(rgt)(0)
                Me.datos_clase.ejecutar(borrar)
            End If
        Next
    End Sub

    Private Function buscar_detalle(ByVal id As String) As busqueda
        Dim tabla As New Data.DataTable
        Dim sql As String

        sql = "SELECT * FROM detalle_factura "
        sql &= " WHERE numero_factura = " & Me.txt_nro_factura.Text
        sql &= " AND id_tipo_factura = " & Me.cmb_tipo_factura.SelectedValue
        sql &= " AND codigo_cd = " & id

        tabla = datos_clase.consulta(sql)

        Select Case tabla.Rows.Count()
            Case 0
                Return busqueda.no_encontro
            Case 1
                Return busqueda.si_encontro
        End Select
        Return True
    End Function

    Private Sub Factura_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If operacion = estado.inicial Then
            If MessageBox.Show("¿Desea salir?", "Alerta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                e.Cancel = True
            End If
        Else
            MessageBox.Show("Termine la operacion actual!", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            e.Cancel = True
        End If
    End Sub

    Private Sub btn_salir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_salir.Click
        Me.Close()
    End Sub

    Private Sub grilla1_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla1.CellDoubleClick
        If MsgBox("Está seguno que desea borrar esta fila de la grilla", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Importante") = MsgBoxResult.Yes Then
            Me.grilla1.Rows.RemoveAt(Me.grilla1.CurrentRow.Index)
            Me.txt_total.Text = Me.calcular_total()
        End If
    End Sub

    Private Sub btn_buscar_factura_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar_factura.Click
        Me.limpiar(Me.Controls)
        limpiar(grp_cliente.Controls)
        limpiar(grp_cd.Controls)
        operacion = estado.modificar
        Buscar_Facturas.ShowDialog()
        If txt_nro_factura.Text <> "" Then
            recuperar_datos()
            botones(False)
            tratamiento.habilitar(True, Me.Controls)
            habilitar_grupo_cd(True)
            habilitar_grupo_cliente(True)
            txt_cantidad.Enabled = True
            cmb_tipo_documento.Enabled = False
            msk_fecha.Focus()
        End If
    End Sub

    Private Sub recuperar_datos()
        Dim sql, sql2 As String
        Dim tabla, tabla2 As New Data.DataTable

        sql = "SELECT * " & _
            " FROM factura " & _
            " WHERE numero_factura = " & Trim(Me.txt_nro_factura.Text) & _
            " AND id_tipo_factura = " & Trim(Me.cmb_tipo_factura.SelectedValue)

        tabla = Me.datos_clase.consulta(sql)

        Me.msk_fecha.Text = tabla.Rows(0)("fecha")
        Me.cmb_tipo_pago.SelectedValue = tabla.Rows(0)("id_tipo_pago")
        Me.cmb_tipo_documento.SelectedValue = tabla.Rows(0)("id_tipo_documento")
        Me.txt_documento.Text = tabla.Rows(0)("numero_documento")

        sql2 = "SELECT nombre, apellido from cliente where numero_documento = '" & tabla.Rows(0)("numero_documento") & "'"
        sql2 &= " and id_tipo_documento = '" & tabla.Rows(0)("id_tipo_documento") & "'"

        tabla2 = Me.datos_clase.consulta(sql2)
        Me.txt_apellido_cliente.Text = tabla2.Rows(0)("apellido")
        Me.txt_nombre_cliente.Text = tabla2.Rows(0)("nombre")


        sql = "SELECT detalle_factura.cantidad, cd.codigo_cd, cd.titulo, detalle_factura.precio" & _
              " FROM (detalle_factura INNER JOIN " & _
              " cd ON detalle_factura.codigo_cd = cd.codigo_cd) " & _
              " WHERE (numero_factura = " & Me.txt_nro_factura.Text & ")" & _
              " AND (id_tipo_factura = " & Me.cmb_tipo_factura.SelectedValue & ")"


        tabla = Me.datos_clase.consulta(sql)

        Dim c As Integer

        For c = 0 To tabla.Rows.Count() - 1
            Me.grilla1.Rows.Add(tabla.Rows(c)("cantidad"), tabla.Rows(c)("codigo_cd") _
                                , tabla.Rows(c)("titulo"), tabla.Rows(c)("precio") _
                                , tabla.Rows(c)("cantidad") * tabla.Rows(c)("precio"))
        Next


    End Sub

    Private Sub limpiar(ByVal de_donde As Object)

        Dim gri As DataGridView

        For Each obj As System.Windows.Forms.Control In de_donde
            Me.grilla1.Rows.Clear()
            Select Case obj.GetType().ToString
                Case "System.Windows.Forms.TextBox"
                    obj.Text = ""
                Case "System.Windows.Forms.MaskedTextBox"
                    obj.Text = ""
                Case "System.Windows.Forms.DataGridView"
                    gri = obj
                    gri.Rows.Clear()
                Case "System.Windows.Forms.GroupBox"
                    Me.limpiar(obj.Controls)
            End Select
        Next obj
    End Sub

    Private Sub btn_cancelar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancelar.Click
        If operacion = estado.insertar Then
            If MessageBox.Show("¿Desea cancelar la operación?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                operacion = estado.inicial
                botones(True)
                tratamiento.habilitar(False, Me.Controls)
                habilitar_grupo_cd(False)
                habilitar_grupo_cliente(False)
                tratamiento.limpiar(Me.Controls)
                tratamiento.limpiar(grp_cd.Controls)
                tratamiento.limpiar(grp_cliente.Controls)
                txt_cantidad.Enabled = False
                grilla1.Rows.Clear()
                btn_nuevo.Focus()
            End If
        Else
            If operacion = estado.modificar Then
                If MessageBox.Show("¿Desea cancelar la modificación?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                    operacion = estado.inicial
                    botones(True)
                    tratamiento.habilitar(False, Me.Controls)
                    habilitar_grupo_cd(False)
                    habilitar_grupo_cliente(False)
                    tratamiento.limpiar(Me.Controls)
                    tratamiento.limpiar(grp_cd.Controls)
                    tratamiento.limpiar(grp_cliente.Controls)
                    txt_cantidad.Enabled = False
                    grilla1.Rows.Clear()
                    btn_nuevo.Focus()
                End If
            End If
        End If
    End Sub

    Private Sub Grupos_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_documento.KeyPress, txt_apellido_cliente.KeyPress, txt_nombre_cliente.KeyPress, txt_codigo_cd.KeyPress, txt_titulo_cd.KeyPress, txt_precio_cd.KeyPress, txt_subtotal_cd.KeyPress
        e.KeyChar = ""
    End Sub

    Private Sub cmb_tipo_factura_SelectionChangeCommitted(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb_tipo_factura.SelectionChangeCommitted
        Dim sql As String = ""
        Dim tabla As New DataTable
        Dim id As Integer = 0

        sql = "SELECT MAX(factura.numero_factura) FROM factura where id_tipo_factura = " & cmb_tipo_factura.SelectedValue
        tabla = datos_clase.ejecutar_sql(sql)
        If IsDBNull(tabla.Rows(0)(0)) Then
            id = 1
        Else
            id = (tabla.Rows(0)(0)) + 1
        End If
        txt_nro_factura.Text = id
    End Sub

    Private Sub txt_nro_factura_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_nro_factura.KeyPress
        e.KeyChar = ""
    End Sub
End Class